﻿//
// GNS_CursorTextField.cpp
// TestPro
//
// Created by mr.l on 16/1/28.
//
//
#include "GNS_CursorTextField.h"

const static float DELTA = 5.0f;

GNS_CursorTextField::GNS_CursorTextField():passworldStyleBool(false),CursorSptHigth(25)
{
    TextFieldTTF();
    
    m_pCursorSprite = NULL;
    m_pCursorAction = NULL;
    passwordStyleText=NULL;
    m_pInputText = NULL;
    m_limitNum = 19;
    
}

GNS_CursorTextField::~GNS_CursorTextField()
{
    delete m_pInputText;
    delete passwordStyleText;
}
//当用户点开虚拟键盘的回调函数
bool GNS_CursorTextField::onTextFieldAttachWithIME(TextFieldTTF * sender)
{
    if (m_pInputText->empty())
    {
        return false;
    }
    setCursorPositionX(getContentSize().width);
    return false;
}
//当用户关闭虚拟键盘的时候回调函数
bool GNS_CursorTextField::onTextFieldDetachWithIME(TextFieldTTF * sender)
{
    return false;
}
//当用户进行输入,虚拟键盘的时候回调函数
bool GNS_CursorTextField::onTextFieldInsertText(TextFieldTTF * sender, const char * text, size_t nLen)
{
    //判断输入的字符个数
    if (m_pInputText->length() > m_limitNum)
    {
        return true;
    }
    m_pInputText->append(text);
    if(passworldStyleBool==false)
    {
        setString(m_pInputText->c_str());
    }else{
        passwordStyleText->append("*");
        setString(passwordStyleText->c_str());
    }
    setCursorPositionX(getContentSize().width);
    return true;
}
//当用户进行删除文字,虚拟键盘的时候回调函数
bool GNS_CursorTextField::onTextFieldDeleteBackward(TextFieldTTF * sender, const char * delText, size_t nLen)
{
    m_pInputText->resize(m_pInputText->size() - nLen);
 
    if (passworldStyleBool==false) {
        setString(m_pInputText->c_str());
    }else{
        passwordStyleText->resize(passwordStyleText->size() - nLen);
        setString(passwordStyleText->c_str());
    }
    setCursorPositionX(getContentSize().width);
    
    if (m_pInputText->empty())
    {
        setCursorPositionX(0);
    }
    return false;
}
//触摸事件
bool GNS_CursorTextField::onTouchBegan(Touch *pTouch, Event *pEvent)
{
    m_beginPos = pTouch->getLocationInView();
    m_beginPos = Director::getInstance()->convertToGL(m_beginPos);
    return true;
}
//触摸事件
void GNS_CursorTextField::onTouchEnded(Touch *pTouch, Event *pEvent)
{
    Point endPos = pTouch->getLocationInView();
    endPos = Director::getInstance()->convertToGL(endPos);
    
    // 判断是否为点击事件
    if (std::abs(endPos.x - m_beginPos.x) > DELTA ||
        std::abs(endPos.y - m_beginPos.y))
    {
        // 不是点击事件
        m_beginPos.x = m_beginPos.y = -1;
        return;
    }

	Rect rect = this->boundingBox();
	bool isTouch = rect.containsPoint(endPos);
	if (isTouch)
	{
		if (m_pInputText->size() <= 0)
		{
			setPlaceHolder("");
		}
	}
	else
	{
		setPlaceHolder(m_tips.c_str());
	}
	
    //判断虚拟键盘是否打开(关闭)
    isInTextField(pTouch) ? openIME() : closeIME();
	
}
// 得到TextField矩形
Rect GNS_CursorTextField::getRect()
{
    Size size = getContentSize();
    return Rect::Rect(/*- size.width / 2*/0, - size.height / 2 -20, size.width + 350, size.height+50);
}
//判断虚拟键盘是否打开(关闭)
bool GNS_CursorTextField::isInTextField(cocos2d::Touch* pTouch)
{
    //这里我先不是很会写，后来终于找到了这样的写法
    return getRect().containsPoint(convertTouchToNodeSpaceAR(pTouch));
}
void GNS_CursorTextField::onEnter()
{
    TextFieldTTF::onEnter();
    ////////触摸调用//////
    //这里的触摸优先级设置为了保证，屏蔽下方的触摸
    auto dispatcher = Director::getInstance()->getEventDispatcher();
    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = CC_CALLBACK_2(GNS_CursorTextField::onTouchBegan,this);
    listener->onTouchEnded = CC_CALLBACK_2(GNS_CursorTextField::onTouchEnded,this);
    listener->setSwallowTouches(false);//true不向下传递触摸,false向下传递触摸
    dispatcher->addEventListenerWithSceneGraphPriority(listener,this);
    //注册监听器写在这里
    this->setDelegate(this);
}

void GNS_CursorTextField::onExit()
{
    TextFieldTTF::onExit();
}
//输入框接收函数
GNS_CursorTextField* GNS_CursorTextField::textFieldWithPlaceHolder( const char *placeholder, const char *fontName, float fontSize )
{
    GNS_CursorTextField *pRet = new GNS_CursorTextField();
    if(pRet && pRet->initWithPlaceHolder("", fontName, fontSize))
    {
        pRet->autorelease();
        if (placeholder)
        {
            pRet->setPlaceHolder(placeholder);
			pRet->m_tips = placeholder;
        }
        pRet->initCursorSprite(fontSize);
        return pRet;
    }
    CC_SAFE_DELETE(pRet);
    return NULL;
}
//初始化光标精灵
void GNS_CursorTextField::initCursorSprite(float fontSize)
{
    int column = 4;
    int nHeight = fontSize;
    int pixels[4][4];
    for (int i=0; i<nHeight; ++i)
    {
        for (int j=0; j<column; ++j)
        {
            pixels[i][j] = 0xffffffff;
        }
    }
    Texture2D* texture = new Texture2D();
    texture->initWithData(pixels,25,Texture2D::PixelFormat::RGB888, 3, fontSize, Size::Size(column, nHeight));
    
    m_pCursorSprite = Sprite::createWithTexture(texture);
    m_pCursorSprite->setColor(Color3B(0,0,0));
    Size winSize = getContentSize();
    
    m_pCursorSprite->setVisible(false);
    
    m_pCursorAction = RepeatForever::create((ActionInterval *) Sequence::create(FadeOut::create(0.25f), FadeIn::create(0.25f), NULL));
    
    m_pInputText = new std::string();
    passwordStyleText = new std::string();
}
//打开虚拟键盘
void GNS_CursorTextField::openIME()
{
    m_pCursorSprite->setVisible(true);
//    TextFieldTTF::
    this->attachWithIME();
}
//关闭虚拟键盘
void GNS_CursorTextField::closeIME()
{
    m_pCursorSprite->setVisible(false);
    
    this->detachWithIME();
}
/////wcz add///////////
void GNS_CursorTextField::setPosition(const Point& pos)
{
    TextFieldTTF::setPosition(pos);
    // 设置光标位置
    if (NULL != m_pCursorSprite)
    {
        Size winSize = getContentSize();
        m_cursorPos = Vec2(0, 0/*winSize.height / 2*/);
        m_cursorPos = m_cursorPos + pos;
        m_pCursorSprite->setPosition(m_cursorPos);
    }
}
void GNS_CursorTextField::setCursorPositionX(float x) // 设置光标x位置
{
    Point pt = getPosition(); // 获取输入框位置
    m_pCursorSprite->setPositionX(pt.x + x);
}
// 把光标添加到和输入框一起的层中
void GNS_CursorTextField::AddCursor(Node *node)
{
    if (NULL != node && NULL != m_pCursorSprite)
    {
        node->addChild(m_pCursorSprite);
        m_pCursorSprite->runAction(m_pCursorAction);
    }
}
void GNS_CursorTextField::setLimitNum(int limitNum)
{
    m_limitNum=limitNum;
}
void GNS_CursorTextField::setPasswordEnabled(bool enable)
{
    passworldStyleBool=enable;
}
std::string & GNS_CursorTextField::getInputString()
{
    return *m_pInputText;
}
